﻿(function($) {
    var global_date = null;
    var global_target = null;

    var global_days_template_count = 42;

    var day_cotent_template = null;
    var day_head_template = null;
    var week_head_template = null;
    var week_content_template = null;
    var week_array_template = null;
    var work_content_template = null;
    var month_select_template = null;
    var month_template = null;
    var day_top_template = null;


    var week_head_array = null;
    var month_days_array = null;

    function calen_init_params() {
        global_date = new Date();

        day_cotent_template = "<span class='[class]'>[day]</span>";
        day_head_template = "<span [class]>[day]</span>";
        week_head_template = "<div class='week'>[week]</div>";
        week_content_template = "<div class='week_content'>[week]</div>";
        work_content_template = "<div id='calen_workare' style='display:none;'><input type='hidden' id='calen_hd_date' /><div id='workarea_note'></div></div>";
        month_select_template = "<div class='month_wrap'><span class='month_year'>[year]年</span><span class='calen_close'></span><div id='monthselect' class='month_list [curr_month]'>[months]</div></div>";
        month_template = "<span id='month[id]' class='item'>[month]月</span>";
        day_top_template = "<div class='day_top'><div class='color_tip'><span class='ui_noted' style='margin-left:30px; margin-right:5px;'>&nbsp&nbsp&nbsp&nbsp</span>笔记" +
            "<span class='ui_unconfirm' style='margin-left:20px; margin-right:5px;'>&nbsp&nbsp&nbsp&nbsp</span>未确认<span class='ui_hurry' style='margin-left:20px; margin-right:5px;'>&nbsp&nbsp&nbsp&nbsp</span>加急</div></div>";

        week_head_array = new Array();
        week_head_array[0] = "sun";
        week_head_array[1] = "mon";
        week_head_array[2] = "tue";
        week_head_array[3] = "wed";
        week_head_array[4] = "thu";
        week_head_array[5] = "fri";
        week_head_array[6] = "sat";

        month_days_array = new Array();
        month_days_array[0] = 0;
        month_days_array[1] = 31;
        month_days_array[2] = 28;
        month_days_array[3] = 31;
        month_days_array[4] = 30;
        month_days_array[5] = 31;
        month_days_array[6] = 30;
        month_days_array[7] = 31;
        month_days_array[8] = 31;
        month_days_array[9] = 30;
        month_days_array[10] = 31;
        month_days_array[11] = 30;
        month_days_array[12] = 31;

        week_array_template = new Array();
    }

    // 初始化插件
    function calen_init() {
        binding_event();
        $(global_target).children("#full_calen").attr("style", "display:none; width:0;");
    }

    // 获得当前年份
    function get_curr_year() {
        return global_date.getFullYear();
    }

    // 获得当前月份
    function get_curr_month() {
        return global_date.getMonth() + 1;
    }

    // 获得当前月的总天数
    function get_curr_days() {
        return calculate_curr_month_days(get_curr_month());
    }

    // 获得当前日期
    function get_curr_date() {
        return get_curr_year() + "-" + get_curr_month() + "-" + get_curr_days();
    }

    // 获得本月一号的星期数
    function get_curr_first_day() {
        var days = calculate_days(get_curr_month());
        var year = get_curr_year();
        /*
        公式: 令 x=year,y=days
        s = x-1 + (x-1)/4 - (x-1)/100 + (x-1)/400 + y;
        s % 7 几位星期数
        */
        var s = year - 1 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + days;
        var weekNum = s % 14;
        weekNum = parseInt(weekNum);
        //        weekNum = weekNum == 0 ? 14 : weekNum;
        return weekNum;
    }

    // 计算本年到当前月份的总天数
    function calculate_days(monthIndex) {
        var days = 0;
        for (var index = 0; index < monthIndex; index++) {
            days += calculate_curr_month_days(index);
        }
        days += 1;
        return days;
    }

    // 计算当前月的天数
    function calculate_curr_month_days(monthIndex) {
        var dayCount = 0;
        if (monthIndex == 2) {
            var intercalary = false;
            if (get_curr_year() % 4 == 0) {
                var curr_year_str = get_curr_year().toString();
                var last_two_num = curr_year_str.substr(curr_year_str.length - 2);

                intercalary = true;
                if (last_two_num == "00") {
                    if (get_curr_year() % 400 != 0)
                        intercalary = false;
                }
            }
            if (intercalary) {
                dayCount = 29;
            } else {
                dayCount = 28;
            }
        } else {
            dayCount = month_days_array[monthIndex];
        }
        return dayCount;
    }

    // 生成当天日期
    function produce_curr_day() {
        var curr_day = "";
        curr_day += "<div class='day_calendar'>";
        curr_day += "<center>";
        curr_day += produce_curr_day_content();
        curr_day += "</center>";
        curr_day += "</div>";
        return curr_day;
    }

    // 生成当天日期体
    function produce_curr_day_content() {
        var curr_day_content = "";
        var date = new Date();
        curr_day_content += "<div class='day_week'>" + getWeek(date.getDay()) + "</div>";
        curr_day_content += "<div class='day_date'>" + date.getDate() + "</div>";
        curr_day_content += "<div class='day_month'>" + date.getFullYear() + "&nbsp" + getMonth(date.getMonth() + 1) + "</div>";
        return curr_day_content;
    }

    // 根据罗马数字获得中文星期
    function getWeek(weekIndex) {
        switch (weekIndex) {
            case 1:
                return "星期一";
            case 2:
                return "星期二";
            case 3:
                return "星期三";
            case 4:
                return "星期四";
            case 5:
                return "星期五";
            case 6:
                return "星期六";
            case 0:
                return "星期天";
            default:
                return "星期一";
        }
    }

    // 根据罗马数字获得月份
    function getMonth(monthIndex) {
        switch (monthIndex) {
            case 1:
                return "一月";
            case 2:
                return "二月";
            case 3:
                return "三月";
            case 4:
                return "四月";
            case 5:
                return "五月";
            case 6:
                return "六月";
            case 7:
                return "七月";
            case 8:
                return "八月";
            case 9:
                return "九月";
            case 10:
                return "十月";
            case 11:
                return "十一月";
            case 12:
                return "十二月";
            default:
                return "一月";
        }
    }

    // 生成月
    function produce_calen_month(monthIndex) {
        var month = "";
        month += "<div class='day_panel'>";
        month += produce_week_head();
        month += "<div class='date'>";
        month += produce_week_content();
        month += "</div>";
        month += "</div>";
        return month;
    }

    // 生成星期
    function produce_week_content() {
        fill_week_array();
        var weeks = "";
        var week = "";

        for (var index = 0; index < global_days_template_count; index++) {
            week += week_array_template[index];
            //            if ((index + 1) % 14 == 0) {
            //                weeks += week_content_template.replace(/\[week\]/, week);
            //                week = "";
            //            }
        }
        return week;
    }

    // 填充星期数组
    function fill_week_array() {
        var days = get_curr_days();
        var first_day = get_curr_first_day();
        var index = null;
        var day_count = 1;

        global_date.setMonth(get_curr_month() - 2);
        var pre_days = calculate_curr_month_days(get_curr_month());
        var pre_day = pre_days - first_day + 1;

        for (index = 0; index < first_day; index++) {
            week_array_template[index] = day_cotent_template.replace(/\[day\]/, pre_day + index).replace(/\[class\]/, "off prev");
        }

        global_date.setMonth(get_curr_month());
        for (index = first_day; index < get_curr_days() + first_day; index++) {
            var date = get_curr_year() + "-" + get_curr_month() + "-" + day_count;
            week_array_template[index] = day_cotent_template.replace(/\[day\]/, day_count).replace(/\[class\]/, 'show_' + get_curr_month());
            day_count++;
        }

        for (index = day_count - 1 + first_day; index < global_days_template_count; index++) {
            //                                                                   计算获得下个月的日子
            week_array_template[index] = day_cotent_template.replace(/\[day\]/, (index + 1) - (day_count - 1 + first_day)).replace(/\[class\]/, "off post");
        }
    }

    // 刷新日历月份内容
    function refresh_calender() {
        var calen_content = produce_calen_content();
        var date = new Date();
        if (get_curr_month() == (date.getMonth() + 1))
            $(global_target).children(".day_calendar").children().children("div:eq(1)").attr("class", "day_date");
        $(global_target).children("#full_calen").children(".month_wrap").children("#monthselect").attr("class", "month_list month_" + get_curr_month());
        $(global_target).children("#full_calen").children(".day_wrap").html(calen_content);
        binding_event();
    }

    // 翻页
    function switch_month(switch_way) {
        if (switch_way == "PRVE") {
            global_date.setMonth(get_curr_month() - 2);
        } else if (switch_way == "NEXT") {
            global_date.setMonth(get_curr_month());
        }
        refresh_calender();
    }

    // 选中月份更新日历
    function selected_month(month_index) {
        var monthIndex = parseInt(month_index);
        global_date.setMonth(monthIndex - 1);
        refresh_calender();
    }

    // 展开日历
    function extend_calender(element, size, speed, callback) {
        //长宽渐变：size:要改变到的尺寸 格式 {width:400, height:250}或{width:400}或{height:250}；speed:速度 1-100，默认为10
        if (typeof (element) == 'string') element = document.getElementById(element);
        $(element).css("display", "block");
        if (!element.effect) {
            element.effect = {};
            element.effect.resize = 0;
        }
        clearInterval(element.effect.resize);
        var speed = speed || 10;
        var start = { width: element.offsetWidth, height: element.offsetHeight };
        var styleArr = [];
        if (!(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.compatMode == 'BackCompat')) {
            //除了ie下border-content式盒模型情况外，需要对size加以修正
            var CStyle = document.defaultView ? document.defaultView.getComputedStyle(element, null) : element.currentStyle;
            if (typeof (size.width) == 'number') {
                styleArr.push('width');
                size.width = size.width - CStyle.paddingLeft.replace(/\D/g, '') - CStyle.paddingRight.replace(/\D/g, '');
            }
            if (typeof (size.height) == 'number') {
                styleArr.push('height');
                size.height = size.height - CStyle.paddingTop.replace(/\D/g, '') - CStyle.paddingBottom.replace(/\D/g, '');
            }
        }
        element.style.overflow = 'hidden';
        var style = element.style;
        element.effect.resize = setInterval(function() {
            for (var i = 0; i < styleArr.length; i++) {
                start[styleArr[i]] += (size[styleArr[i]] - start[styleArr[i]]) * speed / 100;
                style[styleArr[i]] = start[styleArr[i]] + 'px';
            }
            for (var i = 0; i < styleArr.length; i++) {
                if (Math.round(start[styleArr[i]]) == size[styleArr[i]]) {
                    if (i != styleArr.length - 1) continue;
                } else {
                    break;
                }
                for (var i = 0; i < styleArr.length; i++) style[styleArr[i]] = size[styleArr[i]] + 'px';
                clearInterval(element.effect.resize);
                if (callback) callback.call(element);
            }
            if ($(element).width() == 0) {
                $(element).css("display", "none");
            }
        }, 20);
    }

    function show_full_content() {
        if ($("#full_calen").width() == 0) {
            extend_calender('full_calen', { width: 895 });
        } else {
            hide_full_content();
        }
    }

    function hide_full_content() {
        extend_calender('full_calen', { width: 0 });
    }

    // 生成月份列表用于选择
    function produce_month_select() {
        var month = "<span class='on'></span>";
        for (var index = 1; index < 13; index++) {
            month += month_template.replace(/\[id\]/, index).replace(/\[month\]/, index);
        }
        var monthselect = "";
        monthselect = month_select_template.replace(/\[months\]/, month).replace(/\[year\]/, get_curr_year()).replace(/\[curr_month\]/, "month_" + get_curr_month());
        return monthselect;
    }

    // 生成星期标识
    function produce_week_head() {
        var days = "";
        var week = "";
        for (var index = 0; index < 14; index++) {
            var cls = "";
            if (index % 7 == 0)
                cls = "class='spe'";
            else if (index == 13)
                cls = "class='last'";
            days += day_head_template.replace(/\[day\]/, week_head_array[index % 7]).replace(/\[class\]/, cls);
        }
        week += week_head_template.replace(/\[week\]/, days);
        return week;
    }

    // 生成日历头
    function produce_calen_head() {
        var calen_head = "";
        calen_head = "<div class='calender_head'><span class='switch_prve'><<--</span><span id='time_for_show'>" + get_curr_year() +
        "年" + get_curr_month() + "月</span><span class='switch_next'>-->></span></span></div>";
        return calen_head;
    }

    function produce_full_calender() {
        var calen_content = "";
        calen_content += produce_curr_day();
        calen_content += "<div id='full_calen'>";
        //        calen_content += produce_calen_head();
        calen_content += produce_month_select();
        calen_content += "<div class='day_wrap'>";
        //        calen_content += "<div class='day_top'>" +
        //            "<div class='color_tip'><span class='ui_noted' style='margin-left:30px; margin-right:5px;'>&nbsp&nbsp&nbsp&nbsp</span>笔记" +
        //            "<span class='ui_unconfirm' style='margin-left:20px; margin-right:5px;'>&nbsp&nbsp&nbsp&nbsp</span>未确认" +
        //            "<span class='ui_hurry' style='margin-left:20px; margin-right:5px;'>&nbsp&nbsp&nbsp&nbsp</span>加急</div></div>";
        calen_content += day_top_template;
        calen_content += produce_calen_month(get_curr_month());
        calen_content += "</div>";
        calen_content += work_content_template;
        calen_content += "</div>";
        return calen_content;
    }

    // 生成日历内容
    function produce_calen_content() {
        var calen_content = "";
        calen_content += day_top_template;
        calen_content += produce_calen_month(get_curr_month());
        calen_content += "</div>";
        return calen_content;
    }

    // 生成日历
    function produce_calender() {
        calen_init_params();
        return produce_full_calender();
    }

    // 日期单击事件
    function click_day(day) {
        var days = $(global_target).children("#full_calen").children(".day_wrap").children(".day_panel").children(".date").children();
        for (var index = 0; index < days.length; index++) {
            if ($(days[index]).attr("class").indexOf('ui_select_day') != -1) {
                $(days[index]).removeClass("ui_select_day");
            }
        }
        $(day).addClass("ui_select_day");
    }

    // 事件绑定
    function binding_event() {
        //        var switch_next = $(global_target).children(".full_calen").children(".calender_head").children(".switch_next");
        //        $(switch_next).unbind("click");
        //        $(switch_next).bind("click", function() { global_options.workarea_hide(); switch_month("NEXT"); global_options.switch_click(); });

        //        var switch_prev = $(global_target).children(".full_calen").children(".calender_head").children(".switch_prve");
        //        $(switch_prev).unbind("click");
        //        $(switch_prev).bind("click", function() { global_options.workarea_hide(); switch_month("PRVE"); global_options.switch_click(); });

        var days = $(global_target).children("#full_calen").children(".day_wrap").children(".day_panel").children(".date").children();
        $(days).unbind("click");
        $(days).bind("click", function() {
            var date = "";
            if ($(this).attr("class").indexOf("prev") != -1) {
                global_date.setMonth(get_curr_month() - 2);
                date = get_curr_year() + "-" + get_curr_month() + "-";
                global_date.setMonth(get_curr_month());
            } else if ($(this).attr("class").indexOf("post") != -1) {
                global_date.setMonth(get_curr_month());
                date = get_curr_year() + "-" + get_curr_month() + "-";
                global_date.setMonth(get_curr_month() - 2);
            } else {
                date = get_curr_year() + "-" + get_curr_month() + "-";
            }
            date += $(this).html();
            global_options.day_click(date);
            global_options.workarea_show(date);
            workarea_show(date);
            click_day(this);
        })

        var month = $(global_target).children("#full_calen").children(".month_wrap").children("#monthselect").children("span");
        $(month).unbind("click");
        $(month).bind("click", function() {
            workarea_hide();
            var slt_month = $(this).attr("id").substring(5);
            selected_month(slt_month);
            global_options.switch_click();
        });

        var curr_day = $(global_target).children(".day_calendar").children().children(".day_date");
        $(curr_day).unbind("click");
        $(curr_day).bind("click", function() { show_full_content(); })


        var calen_close = $(global_target).children("#full_calen").children(".month_wrap").children(".calen_close");
        $(calen_close).unbind("click");
        $(calen_close).bind("click", function() { workarea_hide(); hide_full_content(); });
    }

    // 事件绑定的用到的参数
    var global_options = null;

    // 默认使用的事件
    function default_event() { }

    // 显示日历工作栏
    function workarea_show(date) { $("#calen_workare").css("display", "block"); $("#calen_hd_date").val(date) }

    // 隐藏日历工作栏
    function workarea_hide() { $("#calen_workare").css("display", "none"); }

    //    // 隐藏日历工作栏
    //    $.fn.hide_calen_workarea = workarea_hide;


    // 获得当前日期
    $.fn.current_date = get_curr_date;

    // 获得当前年份
    $.fn.current_year = get_curr_year;

    // 获得当前月份
    $.fn.current_month = get_curr_month;

    // 获得当前月份总天数
    $.fn.current_days = get_curr_days;

    // 获得本月第一
    $.fn.first_day = get_curr_first_day;

    $.fn.refresh_calender = refresh_calender;

    // 获得本月一号的星期数
    $.fn.selfcalender = function(options) {
        global_target = $(this);
        $(global_target).html(produce_calender());

        var default_options = {
            day_click: default_event,
            switch_click: default_event,
            workarea_show: default_event,
            workarea_hide: default_event
        };
        global_options = $.extend(default_options, options);

        calen_init();
    };

})(jQuery);
